package cn.ycc1.lianzi.service.impl;

import cn.ycc1.lianzi.service.ChatService;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * @author ycc
 * @date 2025/2/12
 */
@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
    private static final Logger logger = LoggerFactory.getLogger(ChatServiceImpl.class);
    private static StringBuilder fullContent = new StringBuilder();
    private String handleGenerationResult(GenerationResult message) {
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
        fullContent.append(content);
        // System.out.println(content);
        return content;
    }

    @Override
    public Flowable<GenerationResult> streamCallWithMessage(Generation gen, Message userMsg)
            throws ApiException, NoApiKeyException, InputRequiredException {
        GenerationParam param = buildGenerationParam(userMsg);
        System.out.println("流式输出内容为：");
        Flowable<GenerationResult> result = gen.streamCall(param);
        System.out.println(result.toString());
        return result;
        // result.blockingForEach(message -> handleGenerationResult(message));

        // System.out.println("完整内容为: " + fullContent.toString());
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                // .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .apiKey("sk-02b5f1d81f1f452da42caa75baedbd6a")
                .model("deepseek-r1")   // 此处以qwen-plus为例，您可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }

}
